import Vuex from 'vuex'

const cookieparser = process.server ? require('cookieparser') : undefined

import { checkToken } from '~/config/api/basicuserservice'

const createStore = () => {
  return new Vuex.Store({
    state: {
      auth: null,
      basicUserInfo:null
    },
    mutations: {
      setAuth(state, auth) {
        state.auth = auth
      },
      setBasicUserInfo:function(state,basicuser){
        state.basicUserInfo=basicuser;
      },
      resetState(state) {
        state.auth = null
        state.basicUserInfo=null
      }
    },
    actions: {
      /**
       * nuxt 初始化
       * @param commit
       * @param req
       */
      nuxtServerInit({ commit, state }, { req }) {
        console.log('nuxt init')
        console.log(req.headers.cookie)
        let auth = null
        if (req.headers.cookie) {
          const parsed = cookieparser.parse(req.headers.cookie)
          try {
            auth = JSON.parse(parsed.auth)
          } catch (err) {
            // No valid cookie found
          }
          commit('setAuth', auth)
        }
      },

    
      /**
       * 获取用户信息
       * @param state
       * @param commit
       * @returns {Promise<void>}
       */
      async getBasicUserInfo({ state, commit }) {
        if (state.basicUserInfo) {
          return
        }
        await checkToken({
          "uid": state.auth
        }).then(res => {
          if (res.sucfla){
            commit('setBasicUserInfo', res.basicuser)
          }
           
        })


      },
    }
  })
}
export default createStore